package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.ResultCode;
import com.atguigu.eduservice.entity.EduCourse;
import com.atguigu.eduservice.entity.EduCourseDescription;
import com.atguigu.eduservice.entity.vo.CourseInfoVO;
import com.atguigu.eduservice.entity.vo.CourseQueryVO;
import com.atguigu.eduservice.entity.vo.CourseWebVO;
import com.atguigu.eduservice.entity.vo.PublishCourseInfoVO;
import com.atguigu.eduservice.mapper.EduCourseMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduCourseDescriptionService;
import com.atguigu.eduservice.service.EduCourseService;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exception.EduException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author zr
 * @since 2021-11-12
 */
@Service
// 添加事务
@Transactional(readOnly = true)
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {
    @Autowired
    private EduCourseDescriptionService eduCourseDescriptionService;
    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private EduChapterService eduChapterService;

    /**
     * 添加课程信息
     *
     * @param courseInfoVO
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public String saveCourseInfo(CourseInfoVO courseInfoVO) {
        if (courseInfoVO == null) {
            throw new EduException(ResultCode.ADD_COURSE_INFO_FAIL);
        }
        // 创建空对象
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVO, eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if (insert == 0) {
            throw new EduException(ResultCode.ADD_COURSE_INFO_FAIL);
        }
        String courseId = eduCourse.getId();
        // 添加课程描述
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(courseInfoVO.getDescription());
        eduCourseDescription.setId(courseId);
        eduCourseDescriptionService.save(eduCourseDescription);
        return courseId;
    }

    /**
     * 根据课程Id查询课程详细信息
     *
     * @param courseId
     * @return
     */
    @Override
    public CourseInfoVO getCourseInfo(String courseId) {
        // 查询课程信息
        EduCourse eduCourse = baseMapper.selectById(courseId);
        // 判空
        if (eduCourse == null) {
            throw new EduException(ResultCode.DATA_ERROR);
        }
        CourseInfoVO courseInfoVO = new CourseInfoVO();
        // 赋值属性
        BeanUtils.copyProperties(eduCourse, courseInfoVO);
        // 查询课程描述信息
        EduCourseDescription courseDescription = eduCourseDescriptionService.getById(courseId);
        courseInfoVO.setDescription(courseDescription.getDescription());
        return courseInfoVO;
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public void updateCourseInfo(CourseInfoVO courseInfoVO) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVO, eduCourse);
        int update = baseMapper.updateById(eduCourse);
        if (update == 0) {
            throw new EduException("修改课程信息失败", 20001);
        }
        // 根据id修改课程描述
        EduCourseDescription description = new EduCourseDescription();
        description.setId(courseInfoVO.getId());
        description.setDescription(courseInfoVO.getDescription());
        eduCourseDescriptionService.updateById(description);
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public PublishCourseInfoVO getPublishCourseInfo(String courseId) {
        PublishCourseInfoVO publishCourseInfoVO = baseMapper.getPublishCourseInfoVO(courseId);
        return publishCourseInfoVO;
    }

    /**
     * 按照条件查询课程列表
     *
     * @param eduCoursePage
     * @param courseQueryVO
     */
    @Override
    public void getCourseConditionInfo(Page<EduCourse> eduCoursePage, CourseQueryVO courseQueryVO) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        // 按照创建时间进行排序
        queryWrapper.orderByDesc("gmt_create");
        // 进行判断 如果条件为空  直接查询所有
        if (courseQueryVO == null) {
            baseMapper.selectList(queryWrapper);
        }
        // 分别取出条件
        String title = courseQueryVO.getTitle();
        String teacherId = courseQueryVO.getTeacherId();
        String subjectId = courseQueryVO.getSubjectId();
        String subjectParentId = courseQueryVO.getSubjectParentId();
        // 进行判断
        if (StringUtils.hasText(title)) {
            queryWrapper.like("title", title);
        }
        if (StringUtils.hasText(teacherId)) {
            queryWrapper.like("teacher_id", teacherId);
        }
        if (StringUtils.hasText(subjectParentId)) {
            queryWrapper.like("subject_parent_id", subjectParentId);
        }
        if (StringUtils.hasText(subjectId)) {
            queryWrapper.like("subject_id", subjectId);
        }

        baseMapper.selectPage(eduCoursePage, queryWrapper);
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public boolean removeCourseById(String courseId) {
        // 根据课程Id删除小节
        eduVideoService.removeVideoByCourseId(courseId);
        // 根据课程Id删除章节
        eduChapterService.removeChapterById(courseId);
        // 根据课程id删除描述  这个地方 描述的Id和课程Id是公用的Id
        eduCourseDescriptionService.removeById(courseId);
        // 根据课程Id删除本课程
        int delete = baseMapper.deleteById(courseId);
        return delete > 0;
    }

    /**
     * 查询热门课程
     *
     * @return
     */
    @Cacheable(value = "hotCourse", key = "'selectIndexList'")
    @Override
    public List<EduCourse> findCourse() {
        // 根据Id进行降序排序 然后取前八个
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        queryWrapper.last("limit 8");
        List<EduCourse> eduCourseList = baseMapper.selectList(queryWrapper);
        return eduCourseList;
    }

    /**
     * 根据讲师Id查询讲师所讲的课程
     *
     * @param teacherId
     * @return
     */
    @Override
    public List<EduCourse> findCourseInfoById(String teacherId) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id", teacherId);
        //按照最后更新时间倒序排列
        queryWrapper.orderByDesc("gmt_modified");
        List<EduCourse> eduCourseList = baseMapper.selectList(queryWrapper);
        return eduCourseList;
    }

    /**
     * 按照条件查询课程
     *
     * @param coursePage
     * @param courseQueryVO
     * @return
     */
    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> coursePage, CourseQueryVO courseQueryVO) {
        // 按照条件查询
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        // 进行判断 如果条件为空  直接查询所有
        if (courseQueryVO == null) {
            baseMapper.selectList(null);
        }
        // 判断条件是否为空 一级分类Id
        else {
            if (StringUtils.hasText(courseQueryVO.getSubjectParentId())) {
                queryWrapper.eq("subject_parent_id", courseQueryVO.getSubjectParentId());
            }
            // 二级分类
            if (StringUtils.hasText(courseQueryVO.getSubjectId())) {
                queryWrapper.eq("subject_id", courseQueryVO.getSubjectId());
            }
            // 关注度
            if (StringUtils.hasText(courseQueryVO.getBuyCountSort())) {
                queryWrapper.orderByDesc("buy_count");
            }
            // 最新
            if (StringUtils.hasText(courseQueryVO.getGmtCreateSort())) {
                queryWrapper.orderByDesc("gmt_create");
            }
            // 价格
            if (StringUtils.hasText(courseQueryVO.getPriceSort())) {
                queryWrapper.orderByDesc("price");
            }
        }
        baseMapper.selectPage(coursePage, queryWrapper);
        List<EduCourse> records = coursePage.getRecords();
        long current = coursePage.getCurrent();
        long pages = coursePage.getPages();
        long size = coursePage.getSize();
        long total = coursePage.getTotal();
        boolean hasNext = coursePage.hasNext();
        boolean hasPrevious = coursePage.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        return map;
    }

    @Override
    public CourseWebVO getCourseFrontInfo(String courseId) {
        return baseMapper.getCourseFrontInfo(courseId);
    }
}
